import { Hono } from "hono";
import postsRouter from "./routes/posts.js";
import commentsRouter from "./routes/comments.js";
import { HTTPException } from "hono/http-exception";
import { cors } from "hono/cors";
import authRouter from "./routes/auth.js";
import { logger } from "hono/logger";
import type { Context } from "./lib/context.js";
import { auth } from "./middleware/auth.js";

const app = new Hono<Context>();

app.use(
  "/*",
  cors({
    origin: (origin) => origin, // Allow any origin
    credentials: true, // Allow credentials
    allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
    allowHeaders: ["Content-Type", "Authorization"],
    exposeHeaders: ["Set-Cookie"],
  }),
);
app.use("/*", auth);
app.use(logger());

app.get("/", (c) => {
  return c.text("Hello Hono!");
});

app.route("/", authRouter);
app.route("/", postsRouter);
app.route("/", commentsRouter);

// Error handling
app.onError((err, c) => {
  console.error("Caught error:", err);

  if (err instanceof HTTPException) {
    return err.getResponse();
  }

  return c.json(
    {
      message: "An unexpected error occurred",
    },
    500,
  );
});

export default app;
